package com.bnq.logc.work

import android.content.Context
import androidx.annotation.NonNull
import androidx.work.*
import java.util.concurrent.TimeUnit

class LogcUploadManager(val context: Context) {

    companion object{

        private var instance: LogcUploadManager? = null

        @Synchronized
        fun getInstance(context: Context):LogcUploadManager{
            if(instance == null){
                instance = LogcUploadManager(context)
            }
            return instance!!
        }
    }

    val TAG_REQUEST = "tag_logc_upload_log_request"
    val TAG_UNIQUE = "tag_logc_upload_log_unique"

    fun hasWorks():Boolean{
        val works = WorkManager.getInstance(context.applicationContext)
            .getWorkInfosForUniqueWork(TAG_UNIQUE).get()
        var has = false
        works.forEach { work->
            if(!work.state.isFinished){
                has = true
                return@forEach
            }
        }
        return has
    }

    fun start(repeatInterval:Long,unit:TimeUnit){
        val request = PeriodicWorkRequest.Builder(
            LogcUploadWorker::class.java,
            repeatInterval,
            unit,
        )
            .addTag(TAG_REQUEST)
            .setInputData(
                Data.Builder()
                    .build()
            )
            //.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
            .build()
        WorkManager.getInstance(context.applicationContext)
            .enqueueUniquePeriodicWork(TAG_UNIQUE, ExistingPeriodicWorkPolicy.REPLACE,request)
    }

    fun cancel(){
        WorkManager.getInstance(context.applicationContext).cancelUniqueWork(TAG_UNIQUE)
    }

}